package com.putong35.common.httprequest.responsecallbacks;

import android.text.TextUtils;

import com.putong35.common.httprequest.Response;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * http 请求response 回调处理类
 *
 * @Author: Peng Weiwei
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017/6/6
 * @Version: 1.0.0
 */
public abstract class StringResponseListener implements BaseResponseListener{

    public abstract void onSuccess(String response);

    public abstract void onFailure(Throwable t, int errorNo, String strMsg);


    @Override
    public void deliverFailureResponse(Throwable t, int errCode, String errStr) {
        String myMsg;
        int myCode;

        if (errCode == Response.ERR_CODE_INVALID_NET && TextUtils.isEmpty(errStr)) {
            // 没有网络
            myMsg = Response.ERR_STR_INVALID_NET;
            myCode = Response.ERR_CODE_INVALID_NET;

        } else {
            // 解析从服务器返回的数据
            try {
                JSONObject jobj = new JSONObject(errStr);
                myCode = jobj.optInt("code", Response.ERR_CODE_SERVER_ERROR);
                myMsg = jobj.optString("message", Response.ERR_STR_SERVER_ERROR);

            } catch (JSONException e) {
                e.printStackTrace();
                // 解析异常， 服务器返回的数据非json格式
                myMsg = errStr;
                myCode = errCode;
            }
        }

        onFailure(t, myCode, myMsg);
    }

    @Override
    public void deliverSuccessResponse(String response) {
        onSuccess(response);
    }

    private Response response;
    @Override
    public void deliverResponse(String response) {
        if (!TextUtils.isEmpty(response)) {
            this.response = new Response(response);
            // 有些http数据的设计，虽然返回的http code是200， 但是仍然会把一部分错误的状态放在数据中。
            if (this.response.isSuccessful()) {
                deliverSuccessResponse(this.response.getDataString());
            } else {
                deliverFailureResponse(new UnknownError(this.response.getMessage()), this.response.getCode(), this.response.getMessage());
            }
        } else {
            // http请求成功了，但是没有给数据。
            onSuccess(null);
        }
    }

    public Response getResponse() {
        return response;
    }
}
